package db

import (
	"database/sql"
	"fmt"
	_ "github.com/taosdata/driver-go/v3/taosRestful"
	"log"
	"logs/config"
)

var TaosDb *sql.DB
var dbErr error

func init() {
	dsn := config.Conf.TdDsn
	TaosDb, dbErr = sql.Open("taosRestful", dsn)
	if dbErr != nil {
		log.Fatalf("Error Open : %v, %v", dsn, dbErr)
	}
	dbErr = TaosDb.Ping()
	if dbErr != nil {
		log.Fatalf("Error Ping : %v, %v", dsn, dbErr)
	}
	_, dbErr = TaosDb.Exec("CREATE DATABASE IF NOT EXISTS `go_logs` PRECISION 'us'")
	if dbErr != nil {
		log.Fatalf("Error CREATE DATABASE : %v, %v", dsn, dbErr)
	}
	_, dbErr = TaosDb.Exec("CREATE STABLE IF NOT EXISTS `go_logs`.`log` (`ts` TIMESTAMP, `level` VARCHAR(8), `trace_id` VARCHAR(64), `thread_name` VARCHAR(64), `class_name` VARCHAR(256), `context` NCHAR(4096)) TAGS (`app_name` VARCHAR(64),`node_id` VARCHAR(64))")
	if dbErr != nil {
		log.Fatalf("Error CREATE STABLE : %v, %v", dsn, dbErr)
	}
	fmt.Printf("connectd [%v]\n", dsn)
}
